"""

.. module:: showdatastore_service
.. moduleauthor:: @author: 

*Description*:

This module contains the ShowDataStoreService class.

*Constants*:

.. seealso:: class :class:`runtime.service.Service`
"""

# Imports
#
import datetime
import threading
import time
import logging

from datastore.database import *
from datastore.resource import *
from datastore.uri import *
from runtime.service import *
from runtime.node import LoggingLevels

# Constants
#

# Classes
#

class ShowDataStoreService(Service):
    """
    **Constants**:
    """
    
    def cb_start(self, uri, action, res):
        """
        :param uri: Uri
        :param action:
        :param res: Resource
        """
        
        self.logger.log(logging.DEBUG, 
            "Show DataStore available at (%s)", self.service_def.api.fetch.uri)
        self.spaces.set_process(self.service_def.api.fetch.uri, self.cb_show)
        self.spaces.set_process(self.service_def.api.all.uri, self.cb_show_all)

    def cb_show(self, uri, action, res):
        """
        :param uri: Uri
        :param action:
        :param res: Resource
        """
        
        try:
            id = int(str(uri.full())[len(self.service_def.api.fetch.uri):])
        except:
            self.logger.log(logging.DEBUG, "Invalid integer id.")
            id = None
        self.logger.log(logging.DEBUG, "Action (%s) id (%s)", action, str(id))
        if action == 'exists':
            if id is None:
                return False
            else:
                try:
                    res_list = self.datastore.get([id])
                except NotFoundException:
                    res_list = []
                return len(res_list) == 1
        elif action == 'get':
            if id is None:
                return None
            else:
                try:
                    res_list = self.datastore.get([id])
                except NotFoundException:
                    res_list = []
                if len(res_list) == 1:
                    res = res_list[0]
                else:
                    return None
            return res
    
    def cb_show_all(self, uri, action, res):
        """
        :param uri: Uri
        :param action:
        :param res: Resource
        """
        
        if action == 'exists':
            return True
        elif action == 'get':
            res = Resource(type='term:base/services/http/response')
            res.content_type = "text/html"
            res.content = """<h1>Admin - View all DataStore Resources</h1>\n
                <table>\n"""
            all = self.datastore.find([(None, None)])
            for r in all:
                id = r.get_id()
                type = r.get_type()
                title = r.dc_title(default='')
                if title == '':
                    if r.metadata_has_key(
                                    Uri('term:base/build/autoload_suffix')):
                        title = r.get_metadata(
                                    Uri('term:base/build/autoload_suffix'))
                    else:
                        title = ''
                u = "/admin/datastore/" + id
                res.content += """<tr>
                    <td><a href="%s">%s</a></td>
                    <td>%s</td>
                    </tr>\n""" % \
                    (u, type, title)
            res.content += """</table>\n"""
            res.content_length = len(res.content)
            return res
